package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.oss.service.FileService;
import com.atguigu.oss.utils.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * @title: FileServiceImpl
 * @Author danghailiang
 * @Date: 2022/9/23 18:39
 * @Version 1.0
 */
@Service
public class FileServiceImpl implements FileService {


    /**
     * 阿里云文件上传
     * @param inputStream 文件流
     * @param module    模块名称
     * @param fileName  文件名字
     * @return
     */
    @Override
    public String upload(InputStream inputStream, String module, String fileName) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);

        // 判断仓库是否存在
        if(!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
            // 不存在创建仓库
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            // 修改创库权限
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicReadWrite);
        }
        // 路径格式化

        // 时间路径
        String datefolder = new DateTime().toString("/yyyy/MM/dd/");

        // 生成uuid随机数拼接新的文件名字，获取文件扩展名
        fileName =  UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));

        //module/2021/12/17/UUID.扩展名
        String key = module + datefolder + fileName;

        // 上传文件流
        ossClient.putObject(OssProperties.BUCKET_NAME, key, inputStream);


        // 关闭连接
        ossClient.shutdown();

        //https://read-file.oss-cn-beijing.aliyuncs.com/avtar/car.jpg
        return "https://" + OssProperties.BUCKET_NAME +"." + OssProperties.ENDPOINT +"/" +key;
    }

    /**
     * 根据路径删除文件
     * @param url
     */
    @Override
    public void remove(String url) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);

        // https://read-file.oss-cn-beijing.aliyuncs.com/avtar/car.jpg
        String host = "https://"+  OssProperties.BUCKET_NAME + "."+ OssProperties.ENDPOINT +"/";
        // avtar/car.jpg
        String objectName = url.substring(host.length());
        ossClient.deleteObject(OssProperties.BUCKET_NAME, objectName);
    }
}